package com.jftone.bh.app.action;

import java.util.ArrayList;
import java.util.List;

import com.jftone.bh.app.config.SysConst;
import com.jftone.bh.app.model.SysMenu;
import com.jftone.bh.app.model.SysRight;
import com.jftone.bh.app.model.SysRole;
import com.jftone.bh.app.service.SysRoleService;
import org.apache.log4j.Logger;
import org.jftone.annotation.Autowired;
import org.jftone.annotation.Controller;
import org.jftone.exception.ActionException;
import org.jftone.exception.ComponentException;
import org.jftone.util.DataMap;
import org.jftone.util.IData;
import org.jftone.util.StringUtil;


@Controller(mapping="/sysRoleAction")
public class SysRoleAction extends BaseAction {

	private Logger logger = Logger.getLogger(SysRoleAction.class);
	
	@Autowired
	private SysRoleService service;
	
	/**
	 * 首页载入
	 * @throws ActionException
	 */
	public void index() throws ActionException{
		IData<String, Object> inData = new DataMap<String, Object>();
		inData.put("parentCode", SysConst.ROOT_CODE);
		try {
			List<SysRole> list  = service.querySysRoles(inData);
			this.putRenderInfo("rightCode", getRightCode());
			this.putRenderInfo("roots", list);
		} catch (Exception e) {
			logger.error("查询角色根节点数据错误:" + e.getMessage(), e);
			throw new ActionException("查询角色根节点数据错误:" + e.getMessage(), e);
		}
		this.render("sys_role_main.html");
	}
	
	/**
	 * 加载子节点
	 * @throws ActionException
	 */
	public void load() throws ActionException{
		IData<String, Object> data = getData();
		String dataCode = data.getString("dataCode", SysConst.ROOT_CODE);
		IData<String, Object> inData = new DataMap<String, Object>();
		inData.put("parentCode", dataCode);
		try {
			List<SysRole> list  = service.querySysRoles(inData);
			this.send(list);
		} catch (Exception e) {
			logger.error("加载角色节点数据错误:"+e.getMessage(), e);
			throw new ActionException("加载角色节点数据错误:"+e.getMessage(), e);
		}
	}
	
	/**
	 * 查询角色信息
	 * @throws ActionException
	 */
	public void query() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		String roleLevel = data.getString("roleLevel", "1");
		IData<String, Object> inData = new DataMap<String, Object>();
		inData.put("parentCode", parentCode);
		String parentRole="-";
		try {
			List<SysRole> roles  = service.querySysRoles(inData);
			if(!parentCode.equals(SysConst.ROOT_CODE)){
				inData.clear();
				inData.put("roleCode", parentCode);
				SysRole role  = service.getSysRole(inData);
				parentRole=role.getRoleName();
			}
			//设置功能按钮
			setMenuFuncDerictive();
			//设置隐藏传值参数
			this.putRenderInfo(SysConst.QUERY_PARAMS, putParam("parentCode", parentCode).putParam("roleLevel", roleLevel).getParam());
			this.putRenderInfo("parentCode", parentCode);
			this.putRenderInfo("parentRole", parentRole);
			this.putRenderInfo("roles", roles);
			this.putRenderInfo("roleLevel", roleLevel);
		} catch (Exception e) {
			logger.error("查询角色节点数据错误"+e.getMessage(), e);
			throw new ActionException("查询角色节点信息错误"+e.getMessage(), e);
		}
		this.render("sys_role.html");
	}
	
	/**
	 * 登录管理控制台
	 * @throws ActionException
	 */
	public void edit() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		short roleLevel = data.getShort("roleLevel");
		String dataId = data.getString("dataId");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("参数传值错误");
			return;
		}
		try {
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("id", Integer.parseInt(dataId));
			SysRole role = service.getSysRole(inData);
			List<SysRole> list  = new ArrayList<SysRole>();
			if(!parentCode.equals(SysConst.ROOT_CODE)){
				inData.clear();
				inData.put("roleLevel", roleLevel-1);
				list  = service.querySysRoles(inData);
			}
			this.putRenderInfo("parents", list);
			this.putRenderInfo("role", role);
			this.render("sys_role_form.html");
		} catch (Exception e) {
			logger.error("编辑角色节点数据错误"+e.getMessage(), e);
			throw new ActionException("编辑角色节点信息错误"+e.getMessage(), e);
		}
		
	}
	
	public void add() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		short roleLevel = data.getShort("roleLevel");
		SysRole role = new SysRole();
		try {
			List<SysRole> list  = new ArrayList<SysRole>();
			if(!parentCode.equals(SysConst.ROOT_CODE)){
				IData<String, Object> inData = new DataMap<String, Object>();
				inData.put("roleLevel", roleLevel-1);
				list  = service.querySysRoles(inData);
			}
			role.setParentCode(parentCode);
			role.setRoleLevel(roleLevel);
			this.putRenderInfo("parents", list);
			this.putRenderInfo("role", role);
		} catch (Exception e) {
			logger.error("新增角色节点数据错误"+e.getMessage(), e);
			throw new ActionException("新增角色节点数据错误"+e.getMessage(), e);
		}
		this.render("sys_role_form.html");
	}
	
	public void save() throws ActionException{
		boolean updateFlag = false;
		IData<String, Object> data = getData();
		String roleId = data.getString("roleId");
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		short roleLevel = data.getShort("roleLevel");
		if(!StringUtil.isBlank(roleId) && StringUtil.isNumber(roleId)){
			updateFlag = true;
		}
		try {
			int resCode = service.saveSysRole(data, updateFlag);
			if(resCode == 1){
				this.alertMsg("角色编码跟数据库中已知编码重复");
				return;
			}
			this.showMsg("系统角色信息"+(updateFlag? "保存" : "新增")+"成功", "?method=query&parentCode"+parentCode+"&roleLevel="+roleLevel);
		} catch (Exception e) {
			logger.error("保存角色信息错误"+e.getMessage(), e);
			throw new ActionException("保存角色信息错误"+e.getMessage(), e);
		}
	}
	
	public void delete() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		short roleLevel = data.getShort("roleLevel");
		String dataId = data.getString("dataId", "");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("参数传值错误");
			return;
		}
		try {
			int resultCode = service.deleteRole(Integer.parseInt(dataId));
			if(resultCode == 1){
				this.alertMsg("数据错误，请刷新后重试");
				return;
			}else if(resultCode == 2){
				this.alertMsg("系统角色下面有子节点，不能删除");
				return;
			}else if(resultCode == 3){
				this.alertMsg("角色有关联的系统用户");
				return;
			}
			this.showMsg("角色信息删除成功", "?method=query&parentCode="+parentCode+"&roleLevel="+roleLevel);
		} catch (Exception e) {
			logger.error("删除角色数据错误"+e.getMessage(), e);
			throw new ActionException("删除角色数据错误"+e.getMessage(), e);
		}
		
	}
	
	/**
	 * 查询当前角色配置权限
	 * @throws ActionException
	 */
	public void confAuth() throws ActionException{
		IData<String, Object> data = getData();
		String dataId = data.getString("dataId", "");
		String moduleCode = data.getString("moduleCode", "");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("非法请求参数！");
			return;
		}
		try {
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("id", Integer.parseInt(dataId));
			SysRole role = service.getSysRole(inData);
			if(null == role){
				this.alertMsg("非法请求");
				return;
			}
			//加载权限数据
			inData.clear();
			inData.put("roleCode", role.getRoleCode());
			List<SysRight> rightList  = service.querySysRight(inData);
			IData<String, String> hasFuncMap = new DataMap<String, String>(); 		//存放已经配置的菜单功能
			for(SysRight obj : rightList){
				hasFuncMap.put(obj.getMenuCode(), obj.getFuncSet());
			}
			rightList.clear();
			rightList=null;
			//加载系统模块
			inData.clear();
			inData.put("parentCode", SysConst.ROOT_CODE);
			List<SysMenu> moduleList  = service.querySysMenu(inData);
			//如果没有权限数据，则默认取第一个模块
			if(StringUtil.isBlank(moduleCode)){
				moduleCode = moduleList.get(0).getMenuCode();
			}
			inData.clear();
			inData.put("MODULE_CODE", moduleCode);
			List<IData<String, Object>> menuList  = service.queryMenuByModul(inData);
			IData<String, List<IData<String, Object>>> menuFuncMap = new DataMap<String, List<IData<String, Object>>>();  //菜单操作功能
			String menuCode = null;
			for(IData<String, Object> menu : menuList){
				inData.clear();
				menuCode = menu.getString("MENU_CODE");
				inData.put("MENU_CODE", menuCode);
				inData.put("DATA_TYPE", SysConst.MENU_FUNC_BTN);
				menuFuncMap.put(menuCode, service.queryFuncByMenu(inData));
			}
			this.putRenderInfo("moduleList", moduleList);			//模型列表
			this.putRenderInfo("moduleCode", moduleCode);			//当前模型编码
			this.putRenderInfo("hasFunc", hasFuncMap);				//已经保存的功能操作
			this.putRenderInfo("menuFunc", menuFuncMap);			//菜单对应的所有功能操作
			this.putRenderInfo("menuList", menuList);				//菜单列表
			this.putRenderInfo("role", role);						//当前角色
		} catch (Exception e) {
			logger.error("加载权限数据错误"+e.getMessage(), e);
			throw new ActionException("加载权限数据错误"+e.getMessage(), e);
		}
		this.render("sys_role_right.html");
	}
	
	public void saveAuth() throws ActionException{
		IData<String, Object> data = getData();
		String roleId = data.getString("roleId", "");
		String moduleCode = data.getString("moduleCode", "");
		String[] menuCodes = data.getArray("menuCode");
		if(StringUtil.isBlank(roleId) || !StringUtil.isNumber(roleId)){
			this.alertMsg("非法请求参数！");
			return;
		}
		try {
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("id", Integer.parseInt(roleId));
			SysRole role = service.getSysRole(inData);
			if(null == role){
				this.alertMsg("非法请求");
				return;
			}
			String roleCode = role.getRoleCode();
			List<SysRight> rightList = new ArrayList<SysRight>();
			if(null != menuCodes){
				String[] funcs = null;
				for(String tmpCode : menuCodes){
					funcs = data.getArray("func_"+tmpCode);
					SysRight obj = new SysRight();
					obj.setRoleCode(roleCode);
					obj.setMenuCode(tmpCode);
					obj.setNodeCode(data.getString("node_"+tmpCode, ""));
					obj.setFuncSet(funcs == null || funcs.length==0? "" : StringUtil.join(funcs, ","));
					rightList.add(obj);
				}
			}
			service.saveRoleRight(roleCode, moduleCode, rightList);
		} catch (ComponentException e) {
			logger.error("加载权限数据错误"+e.getMessage(), e);
			throw new ActionException("加载权限数据错误"+e.getMessage(), e);
		}
		this.showMsg("角色权限信息保存成功", "?method=confAuth&moduleCode"+moduleCode+"&dataId="+roleId);
	}
}
